<template>
    <div ref="chart" class="chart-component"></div>
</template>

<script>
import * as echarts from 'echarts';

export default {
    name: 'ChartComponent',
    props: {
        type: {
            type: Number,
            required: true
        },
        name: {
            type: String,
            required: true
        },
        url: {
            type: String,
            required: true
        }
    },
    data() {
        return {
            unit: 'day',
            duration: 1,
            options: null,
            intervalId: null,
        };
    },
    watch: {
        type() {
            this.GetRecentData();
        }
    },
    mounted() {
        this.chart = echarts.init(this.$refs.chart);
        this.GetRecentData();
        this.intervalId = setInterval(this.GetRecentData, 5 * 60 * 1000);
    },
    beforeDestroy() {
        clearInterval(this.intervalId);
    },
    methods: {
        GenerateOptions(data) {
            return {
                title: {
                    text: this.name,
                    bottom: 0,
                },
                tooltip: {
                    trigger: 'axis'
                },
                xAxis: {
                    type: 'time',
                    axisLabel: {
                    }
                },
                yAxis: {
                    type: 'value',
                    axisLabel: {
                        formatter: function (value) {
                            if (this.type === 0) {
                                return value + ' AQI';
                            } else if (this.type === 1) {
                                return value + ' °C';
                            } else if (this.type === 2) {
                                return value + ' %';
                            } else {
                                return value;
                            }
                        }.bind(this)
                    }
                },
                series: [{
                    type: 'line',
                    data: data.map(item => [item.time, item.value]),
                    showSymbol: false
                }]
            };
        },
        GetRecentData() {
            const requestData = {
                unit: this.unit,
                duration: this.duration
            };
            this.$http.put(this.url, requestData)
                .then(response => {
                    const responseData = response.data;
                    this.options = this.GenerateOptions(responseData.data);
                    this.chart.setOption(this.options);
                }).catch(error => {
                    error;
                });
        },
    },
};
</script>

<style scoped>
.chart-component {
    width: 100%;
    height: 100%;
}
</style>
